/*
 * @Author: zhuxiaoyi
 * @Date: 2024-01-26 14:52:39
 * @LastEditor: zhuxiaoyi
 * @LastEditTime: 2024-07-17 14:17:50
 * @Description:
 */
import { Provide, App, Config } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Task } from '../entity/task.entity';
import { WaterFeature } from '../entity/feature.entity';
import { Algorithm } from '../entity/algorithm.entity';
import { Repository, Like, MoreThan } from 'typeorm';
import { Ipage, ItaskExecute } from '../interface';
import { Application } from '@midwayjs/ws';
import * as childProcess from 'child_process';
import { InjectJob, CronJob } from '@midwayjs/cron';
import { DataSyncCheckerJob, listenTasktoPublish } from '../job/sync.job';
import { basename, dirname, extname, parse } from 'path';
import axios from 'axios';
import * as fs from 'fs';
import * as path from 'path';

const archiver = require('archiver');
@Provide()
export class TaskService {
  @InjectEntityModel(Task)
  taskModel: Repository<Task>;

  @InjectEntityModel(Algorithm)
  AlgorithmModel: Repository<Algorithm>;

  @InjectEntityModel(WaterFeature)
  private waterFeatureModel: Repository<WaterFeature>;

  @App('webSocket')
  wsApp: Application;

  @InjectJob(DataSyncCheckerJob)
  syncJob: CronJob;

  @InjectJob(listenTasktoPublish)
  syncJob1: CronJob;

  async createTask(algorithm: any) {
    try {
      const parameters = JSON.parse(algorithm.parameters);
      const parametersParsed = this.convertJsonArrayToObject(parameters);
      const timestamp = Date.now();
      const taskName = `算法任务_${algorithm.identifier}_${timestamp}`;
      const task = new Task();
      task.name = taskName;
      task.status = 0;
      task.progress = 0;
      task.isPublished = false;
      task.fileName = parametersParsed.fileName;
      task.inputFile = parametersParsed.inputFile;
      task.outputFile = parametersParsed.outputFile;
      task.shpZipFile = parametersParsed.shpZipFile;
      task.fileDate = parametersParsed.fileDate;
      task.satType = parametersParsed.satType;
      task.location = parametersParsed.location;
      task.gisInfo = parametersParsed.gisInfo;
      task.logId = 1;
      task.algorithm = algorithm;
      const savedTask = await this.taskModel.save(task);
      return savedTask;
    } catch (error) {
      console.error('创建任务失败:', error);
      return false; // 返回 false 表示创建任务失败
    }
  }

  async restartTask(id: number) {
    const task = await this.taskModel.findOne({
      where: {
        id:id
      }
    });
    if(!task){
      return {
        success: false,
        message: '任务不存在',
      };
    }else{
      const algorithm = await this.AlgorithmModel.findOne({
        where: {
          id: 15,
        },
      });
      task.algorithm = algorithm;
      await this.randerTif(task);
      return {
        success: true,
        data: task,
        message: '任务重启成功',
      };
    }
  }

  async createTaskAndExecution(taskParams: ItaskExecute) {
    try {
      const task = new Task();
      const { name } = parse(taskParams.outputFile)
      const directoryPath = dirname(taskParams.outputFile); // 文件夹地址

      const dirPath = dirname(this.dataBaseURL + taskParams.outputFile);
      // 检查目录是否存在
      if (!fs.existsSync(dirPath)) {
        // 创建目录及其所有子目录
        fs.mkdirSync(dirPath, { recursive: true });
        console.log(`Directory ${dirPath} created.`);
      } else {
        console.log(`Directory ${dirPath} already exists.`);
      }

      task.name = `水体提取_${taskParams.satType}_${taskParams.location}_${name}`;
      task.fileName = name;
      task.status = 0;
      task.progress = 0;
      task.isPublished = false;
      task.inputFile = taskParams.inputFile;
      task.randerFile = directoryPath + '/' + name + '.tif';
      task.outputFile = taskParams.outputFile;
      task.shpZipFile = directoryPath + '/' + name + '_shp.zip';
      task.fileDate = new Date(taskParams.fileDate);
      task.satType = taskParams.satType;
      task.location = taskParams.location;
      task.gisInfo = taskParams.box;
      task.logId = 1;
      task.preId = taskParams.preId;
      const algorithm = await this.AlgorithmModel.findOne({
        where: {
          id: taskParams.algorithmId,
        },
      });
      task.algorithm = algorithm;

      const existingTask = await this.taskModel.findOne({
        where: {
          name: task.name
        }
      });

      if (existingTask) {
        // 更新现有任务对象的所有属性
        existingTask.fileName = task.fileName;
        existingTask.status = task.status;
        existingTask.progress = task.progress;
        existingTask.isPublished = task.isPublished;
        existingTask.inputFile = task.inputFile;
        existingTask.randerFile = task.randerFile;
        existingTask.outputFile = task.outputFile;
        existingTask.shpZipFile = task.shpZipFile;
        existingTask.fileDate = task.fileDate;
        existingTask.satType = task.satType;
        existingTask.location = task.location;
        existingTask.gisInfo = task.gisInfo;
        existingTask.logId = task.logId;
        existingTask.preId = task.preId;
        existingTask.algorithm = task.algorithm;
        existingTask.updateDate = new Date(); // 更新 updatedAt 时间戳
        await this.taskModel.save(existingTask)
        await this.randerTif(task);
        return {
          success: true,
          data: existingTask,
          message: '任务已存在,已更新'
        };
      } else {
        const savedTask = await this.taskModel.save(task);
        await this.randerTif(task);
        return {
          success: true,
          data: savedTask,
          message: '任务创建成功',
        };
      }
    } catch (error) {
      return {
        success: false,
        data: error,
        message: '任务创建失败',
      };
    }
  }

  async getTaskList(params: Ipage) {
    const [result, total] = await this.taskModel.findAndCount({
      where: { name: Like(`%${params.keyword ? params.keyword : ''}%`) },
      skip: (params.page_index - 1) * params.page_size,
      take: params.page_size,
      order: { createDate: 'DESC' },
    });
    return {
      succes: true,
      data: result,
      total,
      message: '成功',
    };
  }
/*   async getTreeList(location) {
    try {
      const allTasks = await this.taskModel.find({
        order: { fileDate: 'DESC' },
        where: {
          status: MoreThan(2),
          location,
        },
      });

      const treeList = [];

      // 创建一个空的地区对象
      const regions = {};

      // 遍历数据记录
      allTasks.forEach(record => {
        const region = record.location;
        const fileDate = new Date(record.fileDate);
        const year = fileDate.getFullYear();
        const month = (fileDate.getMonth() + 1).toString(); // 月份从0开始，需要加1
        const day = fileDate.getDate().toString();

        // 如果地区不存在，则创建一个新的地区对象
        if (!regions[region]) {
          regions[region] = {};
        }

        // 如果年份不存在，则创建一个新的年份对象
        if (!regions[region][year]) {
          regions[region][year] = {};
        }

        // 如果月份不存在，则创建一个新的月份对象
        if (!regions[region][year][month]) {
          regions[region][year][month] = {};
        }

        // 如果日期不存在，则创建一个新的日期数组
        if (!regions[region][year][month][day]) {
          regions[region][year][month][day] = [];
        }

        // 将数据记录添加到日期数组中
        regions[region][year][month][day].push(record);
      });

      // 构建树状列表   
      for (const region in regions) {
        const regionNode = {
          label: region,
          children: [],
        };

        // 获取年份并倒序排列
        const years = Object.keys(regions[region]).map(Number).sort((a, b) => b - a);
        for (const year of years) {
          const yearNode = {
            label: `${year}年`,
            children: [],
          };

          for (const month in regions[region][year]) {
            const monthNode = {
              label: `${month}月`,
              children: [],
            };

            for (const day in regions[region][year][month]) {
              const dayNode = {
                label: `${day}日`,
                children: regions[region][year][month][day].map(record => ({
                  ...record,
                })),
              };
              monthNode.children.push(dayNode);
            }

            yearNode.children.push(monthNode);
          }

          regionNode.children.push(yearNode);
        }

        treeList.push(regionNode);
      }

      return {
        success: true,
        data: treeList,
        message: '成功',
      };
    } catch (error) {
      return {
        success: false,
        data: null,
        message: '获取树状列表失败',
      };
    }
  } */
    async getTreeList(location) {
      try {
        const allTasks = await this.taskModel.find({
          order: { fileDate: 'DESC' },
          where: {
            status: MoreThan(2),
            location,
          },
        });
    
        const treeList = [];
    
        // 创建一个空的地区对象
        const regions = {};
    
        // 遍历数据记录
        allTasks.forEach(record => {
          const region = record.location;
          const fileDate = new Date(record.fileDate);
          const year = fileDate.getFullYear();
          const month = (fileDate.getMonth() + 1).toString(); // 月份从0开始，需要加1
          const day = fileDate.getDate().toString();
    
          // 如果地区不存在，则创建一个新的地区对象
          if (!regions[region]) {
            regions[region] = {};
          }
    
          // 如果年份不存在，则创建一个新的年份对象
          if (!regions[region][year]) {
            regions[region][year] = {};
          }
    
          // 如果月份不存在，则创建一个新的月份对象
          if (!regions[region][year][month]) {
            regions[region][year][month] = {};
          }
    
          // 如果日期不存在，则创建一个新的日期数组
          if (!regions[region][year][month][day]) {
            regions[region][year][month][day] = [];
          }
    
          // 将数据记录添加到日期数组中
          regions[region][year][month][day].push(record);
        });
    
        // 构建树状列表   
        for (const region in regions) {
          const regionNode = {
            label: region,
            children: [],
          };
    
          // 获取年份并倒序排列
          const years = Object.keys(regions[region]).map(Number).sort((a, b) => b - a);
          for (const year of years) {
            const yearNode = {
              label: `${year}年`,
              children: [],
            };
    
            // 获取月份并倒序排列
            const months = Object.keys(regions[region][year]).map(Number).sort((a, b) => b - a);
            for (const month of months) {
              const monthNode = {
                label: `${month}月`,
                children: [],
              };
    
              // 获取日期并倒序排列
              const days = Object.keys(regions[region][year][month]).map(Number).sort((a, b) => b - a);
              for (const day of days) {
                const dayNode = {
                  label: `${day}日`,
                  children: regions[region][year][month][day].map(record => ({
                    ...record,
                  })),
                };
                monthNode.children.push(dayNode);
              }
    
              yearNode.children.push(monthNode);
            }
    
            regionNode.children.push(yearNode);
          }
    
          treeList.push(regionNode);
        }
    
        return {
          success: true,
          data: treeList,
          message: '成功',
        };
      } catch (error) {
        return {
          success: false,
          data: null,
          message: '获取树状列表失败',
        };
      }
    }

  formatDate(dateString) {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}/${month}/${day}`;
  }
  async deleteTask(id: number) {
    const task = await this.taskModel.findOne({
      where: {
        id,
      },
    });
    if (!task) {
      return {
        succes: false,
        message: '未查询到要删除的数据',
      };
    }

    // 删除单个
    let result = await this.taskModel.remove(task);
    return {
      succes: true,
      data: result.id,
      message: '成功',
    };
  }

  async publishResult(id: number) {
    const task = await this.taskModel.findOne({
      where: {
        id,
      },
      relations: ['algorithm'],
    });
    if (!task) {
      return {
        succes: false,
        message: '未查询到要发布的成果',
      };
    }
    await this.publishTifToGeoServer(task);
    return await this.publishShpFile(task);
  }

  async publishTaskByStatus() {
    const results = await this.taskModel.find({
      where: { status: 1 },
      take: 1,
      relations: ['algorithm'],
    });
    results.map(async (task, index) => {
      await this.publishTifToGeoServer(task);
      await this.publishShpFile(task);
    });
  }

  async changeStatus(id: number, status: number) {
    try {
      const task = await this.taskModel.findOneOrFail({
        where: { id },
        relations: ['algorithm'],
      });
      task.status = status;
      const updatedTask = await this.taskModel.save(task);
      return {
        success: true,
        data: {
          id: updatedTask.id,
          name: updatedTask.fileName,
          status: updatedTask.status,
        },
        message: '任务状态更新成功',
      };
    } catch (error) {
      return {
        success: false,
        message: '任务状态更新失败',
      };
    }
  }

  @Config('algorithmBaseURL')
  algorithmBaseURL;

  @Config('dataBaseURL')
  dataBaseURL;

  @Config('geoServerURL')
  geoServerURL;

  async executeTaskByStatus() {
    const results = await this.taskModel.find({
      where: { status: 0 },
      take: 1,
      relations: ['algorithm'],
    });
    results.map(async task => {
      await this.executeAlgorithm(task);
    });
  }


  async randerTif(task: Task) {
    task.status = 2;
    this.taskModel.save(task);
    this.invoke();
    const algorithm = await this.AlgorithmModel.findOne({
      where: {
        id: 1,
      },
    });
    const exePath = this.algorithmBaseURL + algorithm.application; // 替换为你的exe程序路径
    const parameters = JSON.parse(algorithm.parameters);
    const parametersParsed = this.convertJsonArrayToObject(parameters);
    parametersParsed.inputFile = this.dataBaseURL + task.inputFile;
    parametersParsed.outputFile = this.dataBaseURL + task.randerFile;
    const jsonParameter = JSON.stringify(parametersParsed);
    console.log(jsonParameter);
    // 使用child_process.spawn执行exe程序
    const child = childProcess.spawn(exePath, [jsonParameter]);
    let logOutput = ''; // 用于保存日志信息

    // 监听子进程的标准输出
    child.stdout.on('data', data => {
      logOutput += data.toString('utf-8');
      console.log(data.toString('utf-8'));
      let log = data.toString('utf-8');
      let progress = this.extractNumberFromString(log);
      if (progress) {
        task.progress = progress;
        this.taskModel.save(task); 
        this.invoke();
      }
    });

    // 监听子进程的标准错误输出
    child.stderr.on('data', data => {
      logOutput += data.toString('utf-8');
      console.log(data.toString('utf-8'));
    });

    child.on('exit', async code => {
      console.log('算法执行完成');
      this.executeAlgorithm(task)
    });
    return {
      success: true,
      data: {
        taskId: task.id,
      },
      message: '任务执行成功',
    };
  }

  async executeAlgorithm(task: Task) {
    const algorithm = task.algorithm;
    const exePath = this.algorithmBaseURL + algorithm.application; // 替换为你的exe程序路径
    const parameters = JSON.parse(algorithm.parameters);
    const parametersParsed = this.convertJsonArrayToObject(parameters);
    parametersParsed.ruleFile = this.dataBaseURL + parametersParsed.ruleFile;
    parametersParsed.inputFile = this.dataBaseURL + task.inputFile;
    parametersParsed.outputFile = this.dataBaseURL + task.outputFile;
    const jsonParameter = JSON.stringify(parametersParsed);
    console.log(jsonParameter);
    // 使用child_process.spawn执行exe程序
    const child = childProcess.spawn(exePath, [jsonParameter]);

    let logOutput = ''; // 用于保存日志信息

    // 监听子进程的标准输出
    child.stdout.on('data', data => {
      logOutput += data.toString('utf-8');
      console.log(data.toString('utf-8'));
      let log = data.toString('utf-8');
      let progress = this.extractNumberFromString(log);
      if (progress) {
        task.progress = progress;
        this.taskModel.save(task);
        this.invoke();
      }
    });

    // 监听子进程的标准错误输出
    child.stderr.on('data', data => {
      logOutput += data.toString('utf-8');
      console.log(data.toString('utf-8'));
    });

    child.on('exit', async code => {
      console.log('算法执行完成');
      task.status = 1;
      task.progress = 100;
      this.taskModel.save(task);
      this.invoke();
      await this.publishResult(task.id);
    });
    return {
      success: true,
      data: {
        taskId: task.id,
      },
      message: '任务执行成功',
    };
  }

  extractNumberFromString(str: string): number | null {
    const regex = /(\d+)%/;
    const match = str.match(regex);
    let percentage = null;
    if (match) {
      percentage = parseInt(match[1]);
      return percentage;
    }
    return null; // 如果没有找到数字或字符串不符合格式，则返回 null
  }
  async invoke() {
    this.wsApp.clients.forEach(ws => {
      const message = { cmd: 'task', action: 'refresh' };
      ws.send(JSON.stringify(message));
    });
  }

  async publishShpFile(task: Task) {
    const outputFile = this.dataBaseURL + task.outputFile;
    const shpZipFile = this.dataBaseURL + task.shpZipFile;
    return await this.compressShpToZip(outputFile, shpZipFile, task);
  }

  public async publishTifToGeoServer(task: Task) {
    try {
      const workspace = 'result';
      const tifFilePath = this.dataBaseURL + task.randerFile;
      const layerName = task.fileName;
      // GeoServer 的认证信息，如果不需要认证，可以将这部分省略
      const username = 'admin';
      const password = 'geoserver';

      const restUrl = `${this.geoServerURL}/rest/workspaces/${workspace}/coveragestores/${layerName}/file.geotiff`;

      // 构造认证信息
      const auth = `${username}:${password}`;

      const fileData = await fs.promises.readFile(tifFilePath);

      const response = await axios.put(restUrl, fileData, {
        headers: {
          'Content-Type': 'image/tiff',
          Authorization: `Basic ${Buffer.from(auth).toString('base64')}`,
        },
      });

      console.log('TIFF 文件成功发布到 GeoServer!');
    } catch (error) {
      console.error('发布失败:', error.message);
    }
  }

  async getFeature(id: number) {

    const task = await this.taskModel.findOne({
      where: {
        id,
      },
      relations: ['algorithm', 'waterFeature'],
    });
    if (!task) {
      return {
        succes: false,
        message: '未查询到要发布的成果',
      };
    }
    // const inputFile = task.inputFile;
    // const { name } = parse(inputFile); // 解析文件路径，获取文件名和后缀
    // const directoryPath = dirname(inputFile); // 文件夹地址
    // this.dataBaseURL + directoryPath + '/' + name + '_shp_result.zip';
    const outputPath = this.dataBaseURL + task.shpZipFile;
    const url = `${this.geoServerURL}/wfs?service=WFS&version=1.0.0&request=GetFeature&typeName=result:${task.fileName}_shp&outputFormat=SHAPE-ZIP`;
    const postUrl = 'http://192.168.107.224:8189/kqrs/addShpResultFile';
    const postData = {
      file_path: outputPath,
      pre_id: task.preId,
    };
    console.log(postData)
    try {
      // 发送GET请求获取ZIP包的数据
      const response = await axios.get(url, { responseType: 'arraybuffer' });
      // 将ZIP包保存到指定路径
      /* await fs.writeFileSync(
        this.dataBaseURL + '/slc_sys/push.json',
        JSON.stringify(postData)
      ); */
      await fs.writeFileSync(outputPath, Buffer.from(response.data, 'binary'));
      // 发送POST请求
      const postResponse = await axios.post(postUrl, postData);
      await this.taskModel.save({
        ...task,
        status: 6,
      });
      this.pushStatus(7, task.preId)
      return {
        success: true,
        data: task.fileName,
        message: '矢量推送成功',
      };
    } catch (error) {
      await this.taskModel.save({
        ...task,
        status: 6,
      });
      this.pushStatus(7, task.preId)
      return {
        success: false,
        message: '矢量推送失败，苍穹接口报错，请稍后重试',
      };
    }
  }
  async getFeature2(id: number) {

    const task = await this.taskModel.findOne({
      where: {
        id,
      },
      relations: ['algorithm', 'waterFeature'],
    });
    if (!task) {
      return {
        succes: false,
        message: '未查询到要发布的成果',
      };
    }
    const outputPath = this.dataBaseURL + task.shpZipFile;
    const url = `${this.geoServerURL}/wfs?service=WFS&version=1.0.0&request=GetFeature&typeName=result:${task.fileName}_shp&outputFormat=SHAPE-ZIP`;
    const postUrl = 'http://192.168.107.224:8189/kqrs/addShpResultFile';
    const postData = {
      file_path: outputPath,
      pre_id: task.preId,
    };
    try {
      // 发送GET请求获取ZIP包的数据
      const response = await axios.get(url, { responseType: 'arraybuffer' });
      // 将ZIP包保存到指定路径
      /* await fs.writeFileSync(
        this.dataBaseURL + '/slc_sys/push.json',
        JSON.stringify(postData)
      ); */
      await fs.writeFileSync(outputPath, Buffer.from(response.data, 'binary'));
      // 发送POST请求
      const postResponse = await axios.post(postUrl, postData);
      await this.taskModel.save({
        ...task,
        status: 6,
      });
      return {
        success: true,
        data: task.fileName,
        message: '矢量推送成功',
      };
    } catch (error) {
      await this.taskModel.save({
        ...task,
        status: 6,
      });
      this.pushStatus(7, task.preId)
      return {
        success: false,
        message: '矢量推送失败，苍穹接口报错，请稍后重试',
      };
    }
  }

  async pushResult(id: number) {
    const task = await this.taskModel.findOne({
      where: {
        id,
      },
      relations: ['algorithm', 'waterFeature'],
    });

    if (!task) {
      return {
        succes: false,
        message: '未查询到要发布的成果',
      };
    }
    // 发送 WFS 请求获取地理数据
    try {
      const response = await axios.get(`${this.geoServerURL}/wfs`, {
        params: {
          service: 'WFS',
          version: '1.0.0',
          request: 'GetFeature',
          typeName: 'result:' + task.fileName + '_shp',
          outputFormat: 'application/json', // 设置输出格式为 GeoJSON
        },
      });
      // 获取地理数据
      const geoJSONData = response.data;

      // 将地理数据放入 result 字段
      let coordinates = [];
      await geoJSONData.features.forEach(feature => {
        if (feature.properties.class == 2) {
          coordinates.push(feature.geometry.coordinates[0]);
        }
      });

      const waterFeature = task.waterFeature || new WaterFeature();
      waterFeature.geom = { type: 'MultiPolygon', coordinates };

      await this.waterFeatureModel.save(waterFeature);

      await this.taskModel.save({
        ...task,
        waterFeature,
        status: 6,
      });
      return {
        success: true,
        data: task.fileName,
        message: '矢量推送成功',
      };
    } catch (error) {
      console.error('请求失败：', error);
      return {
        success: false,
        message: '矢量推送失败，请稍后重试',
      };
    }
  }

  private async publishShpToGeoServer(shpFilePath: string, task: Task) {
    try {
      const workspace = 'result';
      const layerName = task.fileName + '_shp';

      // GeoServer 的认证信息，如果不需要认证，可以将这部分省略
      const username = 'admin';
      const password = 'geoserver';

      const restUrl = `${this.geoServerURL}/rest/workspaces/${workspace}/datastores/${layerName}/file.shp`;

      // 构造认证信息
      const auth = `${username}:${password}`;

      const fileData = await fs.promises.readFile(shpFilePath);

      const response = await axios.put(restUrl, fileData, {
        headers: {
          'Content-Type': 'application/zip',
          Authorization: `Basic ${Buffer.from(auth).toString('base64')}`,
        },
      });
      console.log('Shapefile 成功发布到 GeoServer!');
      await this.pushStatus(6, task.preId)
      await this.getFeature2(task.id)
      await this.taskModel.save({
        ...task,
        status: 6,
      });
      return {
        success: true,
        data: task,
        message: '成功发布',
      };
    } catch (error) {
      console.error('发布失败:', error.message);
      return {
        success: false,
        data: error.message,
        message: '发布失败',
      };
    }
  }

  private convertJsonArrayToObject(jsonArray) {
    return jsonArray.reduce((result, item) => {
      result[item.param_name] = item.default_value;
      return result;
    }, {});
  }

  async compressShpToZip(
    shpFilePath: string,
    outputZipPath: string,
    task: Task
  ) {
    const self = this;
    return new Promise(async (resolve, reject) => {
      // 创建一个输出流到指定的 ZIP 文件
      const output = fs.createWriteStream(outputZipPath);
      const archive = archiver('zip', {
        zlib: { level: 9 }, // 设置压缩级别
      });

      // 监听错误事件
      output.on('error', function (err) {
        reject(err);
      });

      // 监听关闭事件
      output.on('close', async function () {
        console.log(archive.pointer() + ' total bytes');
        let result = await self.publishShpToGeoServer(outputZipPath, task);
        resolve(result);
        self.invoke();
      });

      // 绑定输出流到压缩程序
      archive.pipe(output);

      // 获取文件名
      const shpFileName = shpFilePath.split('/').pop().replace('.shp', '');
      // 将与 .shp 文件同名的文件（除了 .zip 文件）添加到压缩程序
      const shpFileDir = path.dirname(shpFilePath);
      return await fs.readdir(shpFileDir, async (err, files) => {
        if (err) {
          reject(err);
        } else {
          files.forEach(file => {
            if (
              (file.startsWith(shpFileName) && file.endsWith('.shx')) ||
              file.endsWith('.dbf') ||
              file.endsWith('.shp') ||
              file.endsWith('.prj')
            ) {
              console.log(file);
              const filePath = path.join(shpFileDir, file);
              const { name, ext } = parse(filePath)
              const newFileName = name + '_shp' + ext
              archive.file(filePath, { name: newFileName });
            }
          });

          // 完成压缩
          await archive.finalize();
        }
      });
    });
  }

  changeListenStatus(status: boolean) {
    if (status) {
      this.syncJob.start();
      this.syncJob1.start();
      return {
        success: false,
        message: '开启自动处理监听',
      };
    } else {
      this.syncJob.stop();
      this.syncJob1.stop();
      return {
        success: false,
        message: '停止自动处理监听',
      };
    }
  }

  async pushStatus(status, id) {
    const url = `http://192.168.107.221:8802/dssWaterPretreatmentSub/update?id=${id}&status=${status}`;
    const data = {
      id,
      status
    };
    try {
      const response = await axios.put(url, data);
      console.log('Response data:', response.data);
      return response.data;
    } catch (error) {
      console.error('Error updating status:', error);
      throw error;
    }
  }

  autoSeg(status) {
    if (status) {
      this.syncJob.start();
    } else {
      this.syncJob.stop();
    }
  }
  autoPublish(status) {
    if (status) {
      this.syncJob1.start();
    } else {
      this.syncJob1.stop();
    }
  }
}
